//SPI master library 
// (c) 2013, M. Raimann
#include "spi_master.h"

/* How to use:
// use spi_master.c/h on master device and spi_slave.c/h on slave device
// adjust clock timing
// adjust pinning
// data transmission is always started from master device with spiMasterReadWrite or spiMasterWrite
// have fun!
*/

void spiMasterInit(void)
{	
    /* Set MOSI, SS and SCK output, all others input */
    SPI_DDR|= ((1<<MOSI_PIN)|(1<<SS_PIN)|(1<<SCK_PIN));
	
	//Enable SPI, Master, set clock rate fck/16
	SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);	

}


//transmit data in both directions (full duplex)
void spiMasterReadWrite (uint8_t * dataout, uint8_t * datain, uint8_t len)
{
	uint8_t i;      
	
	SPI_PORT&=~(1<<SS_PIN);
	_delay_us(ACCESS_DELAY);
	for (i = 0; i < len; i++) {
		 SPDR = dataout[i];
		 while((SPSR & (1<<SPIF))==0);
		 datain[i] = SPDR;
		 
		 _delay_us(ACCESS_DELAY);
	}
	SPI_PORT|=(1<<SS_PIN);
}

// write data to target device without receiving any byte
void spiMasterWrite (uint8_t * dataout, uint8_t len)
{
	uint8_t i;      
	
	SPI_PORT&=~(1<<SS_PIN);
	_delay_us(ACCESS_DELAY);
	for (i = 0; i < len; i++) {
		 SPDR = dataout[i];
		 while((SPSR & (1<<SPIF))==0);
		 _delay_us(ACCESS_DELAY);
	}
	SPI_PORT|=(1<<SS_PIN);
}


